<template>
  <div class="mainua">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="main_crumbs boxdq">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>新增集团客户</span>
          </div>
        </div>
        <div class="main_tile boxdq marginTop10">
          <div class="main_tile_l"></div>
        </div>
        <div class="maincla_form">
          <el-form
            ref="form"
            :model="detail"
            label-width="120px"
            :rules="rules"
          >
            <el-form-item label="集团名称" prop="name">
              <el-input v-model="detail.name"></el-input>
            </el-form-item>
            <el-form-item label="负责人" prop="head">
              <el-input v-model="detail.head" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="detail.mobile" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="所在地" prop="base_address">
              <el-select
                v-model="firstId"
                placeholder=""
                @change="selectAction($event, 'firstId')"
              >
                <el-option
                  v-for="item in firstList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <el-select
                v-model="secondId"
                placeholder=""
                @change="selectAction($event, 'secondId')"
              >
                <el-option
                  v-for="item in secondList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <el-select
                v-model="thiredId"
                placeholder=""
                @change="selectAction"
              >
                <el-option
                  v-for="item in thiredList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <div
              class="flex"
              v-for="(citem, index) in detail.company_list"
              :key="index"
            >
              <div>
                <el-form-item label="子公司" prop="company_list">
                  <el-autocomplete
                    v-model.trim="citem.company_name"
                    :ref="'company_name' + index"
                    :fetch-suggestions="queryCustoms"
                    value-key="company_name"
                    placeholder="请输入子公司名称"
                    @select="selectCustom($event, index, 'search')"
                  >
                    <template slot-scope="{ item }">
                      <div>{{ item.company_name }}</div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </div>

              <div class="ads">
                <el-radio v-model="detail.company_id_domain" :label="citem.id"
                  >&nbsp;
                </el-radio>
                <el-button
                  v-if="index == detail.company_list.length - 1"
                  style="margin-left: 5px"
                  icon="el-icon-plus"
                  @click="handleAdd"
                ></el-button>
                <el-button
                  v-if="index != 0"
                  style="margin-left: 5px"
                  icon="el-icon-delete"
                  @click="handleDelete(index)"
                ></el-button>
              </div>
            </div>

            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="detail.remark"
                class="address"
                type="textarea"
                :rows="2"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <div>
                <el-button type="primary" @click="onSubmit">保存</el-button>
                <el-button @click="$router.back()">取消</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { addGroupClient, searcompanylist } from "@/api/user/userGroup";
import { regionListByPid } from "@/api/global/provinces";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
export default {
  data() {
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };

    var checkAdd = (rule, value, callback) => {
      if (this.firstId && this.secondId && this.thiredId) {
        return callback();
      } else {
        return callback(new Error("请选择所在地"));
      }
    };

    var check = (rule, value, callback) => {
      if (value[0].company_name != "") {
        return callback();
      } else {
        callback(new Error("至少添加一个子公司"));
      }
    };

    return {
      detail: {
        company_name: "",
        company_id_domain: "",
        company_list: [
          {
            company_name: "",
            id: ""
          }
        ]
      },
      rules: {
        name: [{ required: true, message: "请输入客户名称", trigger: "blur" }],
        head: [
          { required: true, message: "请输入负责人名称", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入号码", trigger: "blur" },
          { validator: checkPhone, message: "号码格式错误", trigger: "change" }
        ],
        base_address: [
          { validator: checkAdd, required: true, trigger: "change" }
        ],

        company_list: [
          { required: true, message: "请输入子公司名称", trigger: "blur" },
          {
            validator: check,
            message: "请至少添加一个子公司",
            trigger: "change"
          }
        ]
      },
      firstList: [],
      secondList: [],
      thiredList: [],
      firstId: "",
      secondId: "",
      thiredId: ""
    };
  },
  mounted() {
    this.getProvinces("0", 1);
  },
  methods: {
    getProvinces(pid, lv) {
      if (pid) {
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name), { pid }) +
                apiUrl().appsecret
            )
          },
          apiUrl().name,
          { pid }
        );
        regionListByPid(data).then(res => {
          if (res.errcode == 0) {
            if (lv == 1) {
              this.firstList = res.data.list;
            } else if (lv == 2) {
              this.secondList = res.data.list;
            } else if (lv == 3) {
              this.thiredList = res.data.list;
            }
          } else {
            this.$message.error(res.errmsg);
          }
        });
      }
    },

    selectAction(e, type) {
      if (type == "firstId") {
        this.secondList = [];
        this.secondId = null;
        this.thiredList = [];
        this.thiredId = null;
        this.getProvinces(e, 2);
      } else if (type == "secondId") {
        this.thiredList = [];
        this.thiredId = null;
        this.getProvinces(e, 3);
      } else {
        this.detail.base_address = e;
      }
      this[type] = e;
    },
    //搜索子公司
    queryCustoms(str, callback) {
      let params = { company_name: this.detail.company_name };
      searcompanylist(params).then(res => {
        if (res.errcode == 0) {
          let list = [];
          list = res.data.list.filter(e => {
            let flag = false;
            this.detail.company_list.map(c => {
              if (e.id == c.id) {
                flag = true;
              }
            });
            if (!flag) return e;
          });
          callback(list);
        } else {
          callback([]);
          this.$message.error(res.errmsg);
        }
      });
    },
    //选择
    selectCustom(e, index, type) {
      this.detail.company_list[index].id = e.id;
      if (
        !this.detail.company_id_domain ||
        this.detail.company_list.length == 1
      ) {
        this.detail.company_id_domain = e.id;
      }
    },
    handleAdd() {
      this.detail.company_list.push({
        company_name: "",
        radio: "",
        id: ""
      });
    },
    // 删除子公司
    handleDelete(index) {
      if (this.detail.company_list.length > 1) {
        if (
          this.detail.company_id_domain == this.detail.company_list[index].id
        ) {
          this.detail.company_id_domain = this.detail.company_list[0].id;
        }
        this.detail.company_list.splice(index, 1);
      } else {
        this.$message.warning("至少保留一个子公司");
      }
    },

    //保存按钮
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(valid);
          let arr = [];
          this.detail.company_list.map(e => {
            arr.push(e.id);
          });
          let ids = arr.join(",");
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              )
            },
            apiUrl().name,
            {
              company_ids: ids,
              base_address: this.detail.base_address,
              company_id_domain: this.detail.company_id_domain,
              name: this.detail.name,
              head: this.detail.head,
              mobile: this.detail.mobile,
              remark: this.detail.remark
            }
          );
          addGroupClient(data).then(res => {
            if (res.errcode == 0) {
              this.$message.success("添加成功");
              this.$router.go(-1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/.el-form-item__content > .el-input {
  width: 350px;
}
/deep/.el-select {
  width: 114px;
  .el-input__inner {
    width: 100% !important;
  }
}
.btns {
  margin: 20px 110px 0;
  button {
    margin-right: 10px;
  }
}
.address {
  max-width: 350px;
}
.flex {
  display: flex;
}
.flex-margin {
  padding: 0px 10px 0px 0px;
}
.ads {
  line-height: 32px;
  margin-left: 10px;
}
/deep/.el-radio {
  margin-right: 0px !important;
}
</style>
